<template>
    <popup
        ref="popupRef"
        :title="popupTitle"
        :async="true"
        width="550px"
        @confirm="handleSubmit"
        @close="handleClose"
    >
        <el-form ref="formRef" :model="formData" label-width="84px" :rules="formRules">
            
            <el-form-item label="上级部门" prop="pid" v-if="!!formData.pid">
                
                <el-tree-select
                    class="flex-1"
                    v-model="formData.pid"
                    
                    
                    :data="optionsData.dept"
                    clearable
                    node-key="id"
                    :props="{
                            value: 'id',
                            label: 'name'
                        }"
                    check-strictly
                    :default-expand-all="true"
                    placeholder="请选择上级部门"
                />
            </el-form-item>
            
            
            <el-form-item label="部门名称" prop="name">
                <el-input
                    v-model="formData.name"
                    placeholder="请输入部门名称"
                    clearable
                    :maxlength="100"
                />
            </el-form-item>
            
            <el-form-item label="负责人" prop="duty">
                <el-input
                    v-model="formData.duty"
                    placeholder="请输入负责人姓名"
                    clearable
                    :maxlength="30"
                />
            </el-form-item>
            
            <el-form-item label="联系电话" prop="mobile">
                <el-input v-model="formData.mobile" placeholder="请输入联系电话" clearable/>
            </el-form-item>
            
            
            <el-form-item label="排序" prop="isStop">
                <div>
                    <el-input-number v-model="formData.sort" :min="0" :max="9999"/>
                    <div class="form-tips">默认为0， 数值越大越排前</div>
                </div>
            </el-form-item>
            
            
            <el-form-item label="部门状态" prop="isStop">
                <el-switch v-model="formData.isStop" :active-value="0" :inactive-value="1"/>
            </el-form-item>
        
        
        </el-form>
    
    </popup>
</template>

<script lang='ts' setup>


import {FormInstance} from "element-plus";
import Popup from "@/components/popup/index.vue"
import feedback from "@/utils/feedback";
import BeachRequestManager from "@/manager/base/BeachRequestManager";
import {UnwrapNestedRefs} from "@vue/reactivity";
import {deptAdd, deptEdit, getDepartmentList, getDeptDetail} from "@/api/system/SystemAuthDeptController";


const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()

const formData = reactive({
    id: '',
    pid: 0 as string | number,
    name: '',
    duty: '',
    mobile: '',
    sort: 0,
    isStop: 0
})


/**
 * 计算标题
 */
const mode = ref('add')
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑部门' : '新增部门'
})


/**
 * 确定
 */
const emit = defineEmits(['success', 'close'])

async function handleSubmit() {
    await formRef.value?.validate()
    mode.value == 'edit' ? await deptEdit(formData) : await deptAdd(formData)
    
    popupRef.value?.close()
    feedback.msgSuccess('操作成功')
    emit('success')
    
}

/**
 * 取消
 */
function handleClose() {
    emit('close')
}


/**
 * 获取批次请求回响应数据
 */
const optionsData: UnwrapNestedRefs<any> = BeachRequestManager.useBeachRequest({
    dept: {api: getDepartmentList}
})


/**
 * 提供父类调用打开弹窗
 *
 * @param type
 */
function open(type = 'add') {
    mode.value = type
    popupRef.value?.open()
    
}


/**
 * 赋值
 *
 * @param data
 */
async function setFormData(data: Record<any, any>) {
    
    if (!!data) {
        await getDeptDetail({id: data.pid}).then(rsf => {
            for (const key in formData) {
                if (!!rsf[key]) {
                    //@ts-ignore
                    formData[key] = data[key]
                }
            }
            
        })
    }
    
    
}


const formRules = {
    pid: [
        {
            required: true,
            message: '请选择上级部门',
            trigger: ['change']
        }
    ],
    name: [
        {
            required: true,
            message: '请输入部门名称',
            trigger: ['blur']
        }
    ],
    duty: [
        {
            required: true,
            message: '请输入负责人姓名',
            trigger: ['blur']
        }
    ],
    mobile: [
        {
            required: true,
            message: '请输入联系电话',
            trigger: ['blur']
        },
        {
            validator: checkMobile,
            trigger: ['blur']
        }
    ]
}

/**
 * 校验手机号
 *
 * @param rule
 * @param value
 * @param callback
 */
function checkMobile(rule: any, value: any, callback: any) {
    if (!value) {
        return callback()
    } else {
        const reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
        
        if (reg.test(value)) {
            callback()
        } else {
            return callback(new Error('请输入正确的手机号'))
        }
    }
}

defineExpose({
    open,
    setFormData,
})
</script>

<style lang="scss" scoped>

</style>